package com.rabbit.rabbitmq.send;

import cn.hutool.core.util.ObjectUtil;
import com.rabbit.component.RabbitMqComponent;
import com.rabbit.entity.User;
import com.rabbit.utils.RabbitMqUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class SendMsg {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RabbitMqUtil rabbitMqUtil;

    @Resource
    private RabbitMqComponent rabbitMqComponent;

    /**
     * 发送消息
     *
     * @param
     * @return
     */
    @RequestMapping("/sendMsg")
    public String sendMsg() {
        String msg = "this is msg,type:" + "1";
        List<User> userList = new ArrayList<>();
        User user = new User();
        user.setPassWord("hello");
        user.setUserName("myName");
        User user1 = new User();
        user1.setPassWord("hello");
        user1.setUserName("myName");
        userList.add(user);
        userList.add(user1);
        if (true) {
            rabbitTemplate.convertAndSend("kh1.exchange", "springboot.routingKey1", userList);
        }
        if (true) {
            rabbitTemplate.convertAndSend("kh1.exchange", "springboot.routingKey2", userList);
        }
        return "success";
    }

    @RequestMapping("/test")
    public String test() {
        rabbitMqComponent.sendMessage(new User());
        return "helo";
    }

    /**
     * 判断是否存在该队列 存在则进行消息发送
     * 生产者
     *
     * @param user
     */
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestBody User user) {
        try {
            // 创建队列
            rabbitMqUtil.createQueue("kanghui");
            // 创建交换机
            rabbitMqUtil.createExchange("khExchange", "direct");
            // 队列绑定至交换机上
            rabbitMqUtil.queueBinding("one", "kanghui", "khExchange");
        } catch (Exception e) {
            log.info("exception！" + e.getMessage());
        }
        // 发送消息
        if (ObjectUtil.isNotNull(user)) {
            rabbitTemplate.convertAndSend("khExchange", "one", user);
            System.out.println("send success!");
        } else {
            log.info("error！userInfo is null");
        }
    }
}
